// 上个月第一天
function getPreDay(t) {
    var nowdays = new Date(t)
    var year = nowdays.getFullYear()
    var month = nowdays.getMonth()
    if (month == 0) {
        month = 12
        year = year - 1
    }
    if (month < 10) {
        month = '0' + month
    }
    var startDate = year + '-' + month + '-01 00:00:00' //上个月第一天
    return new Date(startDate).getTime()
}


// 加0
function addZero(t){
    t = t< 10? '0' + t : t
    return t
}

/*获取下个月的最后一天*/
let nextMonthLastDay = (t) => {
    var time = new Date(t)
    var year = time.getFullYear()
    var month = time.getMonth() + 2
    if (month > 12) {
        month = month - 12
        year = year + 1
    }
    var day = nextMonthDay(year, month)
    return new Date(year + '-' + addZero(month) + '-' + addZero(day)).getTime()
}
let nextMonthDay = (year, month) => {
    //判断每月多少天
    var day31 = [1, 3, 5, 7, 8, 10, 12]
    var day30 = [4, 6, 9, 11]
    if (day31.indexOf(month) > -1) {
        return 31
    } else if (day30.indexOf(month) > -1) {
        return 30
    } else {
        if (isLeapYear(year)) {
            return 29
        } else {
            return 28
        }
    }
}
let isLeapYear = (year) => {
    //判断是否为闰年
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}


// 当前月的第一天和最后一天
function currentMonthFirstDayAndLastDay(){
    var now = new Date() // 当前日期
    var nowYear = now.getFullYear() //当前年
    var nowMonth = now.getMonth() //当前月 （值为0~11）
    var d = now.getDate() //当天
    var firstDay = new Date(nowYear,nowMonth,1)  // 本月开始时间
    var LastDay = new Date(nowYear, nowMonth+1,0); // 本月结束时间
    var toDay = new Date(nowYear,nowMonth,d) // 本月今天
    //如果想获取本月第一天00：00和最后一天23：59
    //var firstDay = new Date(nowYear,nowMonth,1,00,00)
    //var LastDay = new Date(nowYear, nowMonth+1,0, 23,59);
    //var toDay = new Date(nowYear, nowMonth, d, 23,59,59); // 获取今天23时:59分:59秒
    return {
        firstDay,
        LastDay
    }
}

function formaDate(timer){
        // 定义格式化封装函数
        try {
            function formaData(timer) {
                const year = timer.getFullYear()
                const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
                const day = timer.getDate()
                const hour = timer.getHours()
                const minute = timer.getMinutes()
                const second = timer.getSeconds()
                return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`
            }
            // 定义具体处理标准
            // timeEl 传递过来具体的数值：年月日时分秒
            // total 字符串总长度 默认值为2
            // str 补充元素 默认值为"0"
            function pad(timeEl, total = 2, str = '0') {
                return timeEl.toString().padStart(total, str)
            }
            console.log(formaData(timer));
            return formaData(timer)
        } catch (error) {
            return timer
        }
}

export { nextMonthLastDay, getPreDay, currentMonthFirstDayAndLastDay,formaDate }
